<?php
/**
 * 零起飞-(07FLY-CRM)
 * ==============================================
 * 版权所有 2015-2028   成都零起飞网络，并保留所有权利。
 * 网站地址: http://www.07fly.xyz
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ==============================================
 * Channelor: kfrs <goodkfrs@QQ.com> 574249366
 * Date: 2019-10-3
 */

namespace app\workflow\logic;

use app\common\logic\TableField;

/**
 * 模型字段逻辑
 */
class WorkflowDiyField extends WorkflowBase
{
    /**
     * 析构函数
     */
    function __construct()
    {
        $this->tablefield = new TableField();
    }

    /**
     * 模型字段处列表
     */
    public function getWorkflowDiyFieldList($where = [], $field = true, $order = '', $paginate = DB_LIST_ROWS)
    {

        $list = $this->modelWorkflowDiyField->getList($where, $field, $order, $paginate);
        foreach ($list as &$row) {
            $row['field_type_text'] = $this->modelWorkflowDiyField->field_type_list($row['field_type']);
        }
        return $list;
    }

    /**
     * 模型字段处列表
     */
    public function getFieldsTypeList()
    {
        return $this->modelWorkflowDiyField->field_type_list();
    }

    /**
     * 模型管理处信息
     */
    public function getWorkflowDiyFieldInfo($where = [], $field = true)
    {
        return $this->modelWorkflowDiyField->getInfo($where, $field);
    }

    /**
     * 模型添加
     */
    public function workflowDiyFieldAdd($data = [])
    {
        $validate_result = $this->validateWorkflowDiyField->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateWorkflowDiyField->getError()];
        }
        $data['data_type'] = $this->modelWorkflowDiyField->field_type_list($data['field_type'])['type'];

        //判断扩展表中字段是否存在
        $map['field_name'] = $data['field_name'];
        $map['ext_table'] = $data['ext_table'];
        $field = $this->modelWorkflowDiyField->getValue($map, 'field_name');
        if ($field) {
            throw_response_error('字段名称已经存在！');
        }

        //增加字段
        $this->logicTableField->add_field(SYS_DB_PREFIX . $data['ext_table'], $data['field_name'], $data['data_type'], $data['max_length'], $data['field_default'], $data['field_desc']);


        $result = $this->modelWorkflowDiyField->setInfo($data);
        $url = url('show');
        $result && action_log('新增', '新增自定义表单字段，table：' . $data['ext_table'] . ',field:' . $data['field_name']);

        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelWorkflowDiyField->getError()];
    }

    /**
     * 模型编辑
     */
    public function workflowDiyFieldEdit($data = [])
    {

        $validate_result = $this->validateWorkflowDiyField->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateWorkflowDiyField->getError()];
        }

        $data['data_type'] = $this->modelWorkflowDiyField->field_type_list($data['field_type'])['type'];
        $result = $this->modelWorkflowDiyField->setInfo($data);

        //更新字段
        $this->logicTableField->modify_field(SYS_DB_PREFIX . $data['ext_table'], $data['field_name'], $data['data_type'], $data['max_length'], $data['field_default'], $data['field_desc']);

        $result && action_log('编辑', '编辑自定义表单字段，name：' . $data['ext_table'] . ',field:' . $data['field_name']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '编辑模型字段', $url] : [RESULT_ERROR, $this->modelWorkflowDiyField->getError()];
    }

    /**
     * 字段删除
     */
    public function workflowDiyFieldDel($data = [])
    {
        if(empty($data['id'])){
            throw_response_error('无删除数据');
        }

        //删除字段
        $where['id']=['in',$data['id']];
        $list = $this->modelWorkflowDiyField->getList($where, 'ext_table,field_name', '', false);
        foreach ($list as $row) {
            $this->tablefield->del_field(SYS_DB_PREFIX . $row['ext_table'], $row['field_name']);
        }

        //删除数据
        $result = $this->modelWorkflowDiyField->deleteInfo($where, true);

        $result && action_log('删除', '模型字段，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '字段删除成功'] : [RESULT_ERROR, $this->modelWorkflowDiyField->getError()];
    }


    /**
     * 模型字段处列表
     */
    public function getExtTableFieldList($main_table = null, $ext_table = null)
    {
        if ($main_table && $ext_table) {
            $where['main_table'] = ['=', $main_table];
            $where['ext_table'] = ['=', $ext_table];
            return $this->modelWorkflowDiyField->getList($where, true, 'sort asc', false)->toArray();
        }
    }

    /**
     * 扩展字段=>html代码
     * @param $table
     * @param $value
     * @return mixed
     * @author: 开发人生 goodkfrs@qq.com
     * @Time: 2023/4/9 14:51
     */
    public function getFieldExtHtml($diyid, $value = [])
    {
        //表单信息
        $tableinfo = $this->logicWorkflowDiyForm->getWorkflowDiyFormInfo(['id' => $diyid]);

        return $this->modelWorkflowDiyField->getFieldExtHtml($tableinfo['ext_table'], $value);
    }

    //获得相关的字段
    public function getFieldExtFields($diyid, $type = 'require', $field = 'show_name,field_name,is_list_sort')
    {

        //表单信息
        $tableinfo = $this->logicWorkflowDiyForm->getWorkflowDiyFormInfo(['id' => $diyid]);

        $where['ext_table'] = ['=', $tableinfo['ext_table']];
        switch ($type) {
            //必填字段
            case 'require':
                $where['is_require'] = ['=', 1];
                break;
            //列表显示字段
            case 'list':
                $where['is_list'] = ['=', 1];
                break;
            //可搜索字段
            case 'search':
                $where['is_search'] = ['=', 1];
                break;
            //启用字段，且表单显示
            case 'visible_form':
                $where['is_form'] = ['=', '1'];
                $where['visible'] = ['=', '1'];
                break;
            //启用字段
            case 'visible':
                $where['visible'] = ['=', '1'];
                break;
        }
        $list = $this->modelWorkflowDiyField->getList($where, $field, 'sort asc', false)->toArray();
        return $list;
    }


    /**
     * 根据输入项目，检查表中的必填项
     * @param $table
     * @param $input_values
     * @return void
     * @author: 开发人生 goodkfrs@qq.com
     * @Time: 2023/4/9 21:17
     */
    public function chkFieldExtRequire($table, $input_values = [])
    {

        //获得传过来的数组，得到需要检查的字段名
        $chk_fields = array_keys($input_values);

//        d('传过来值：');
//        d($chk_fields);
//        d($input_values);

        //查取启用字段，必填字段，检查来源字段
        $where['ext_table'] = ['=', $table];
        $where['is_require'] = ['=', 1];
        $where['visible'] = ['=', 1];//
        $where['field_name'] = ['in', $chk_fields];
        $list = $this->modelWorkflowDiyField->getList($where, 'show_name,field_name,is_require', 'sort asc', false)->toArray();

//        d('根据要求要检查字段：');
//        d($list);

        foreach ($list as $row) {
            if (empty($input_values[$row['field_name']])) {
                throw_response_error($row['show_name'] . '字段必须填写');
            }
        }
    }

}
